package com.fau.wm.util;

import org.apache.log4j.Logger;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * @desc 汉字转拼音首字母
 * @author liy
 * @datetime 2014年12月18日,下午10:44:13
 */
public class ChineseTransformUtil {
	
	private static final Logger log = Logger.getLogger(ChineseTransformUtil.class);
	
	/**
	 * @desc 获得汉字首拼音字母，英文字符不变
	 * @param chinese 汉字
	 * @return String
	 * @author liy
	 * @datetime 2014年12月18日,下午11:04:59
	 */
	public static String firstSpell(String chinese) {
		StringBuilder builder = new StringBuilder();
		char[] arr = chinese.toCharArray();
		
		HanyuPinyinOutputFormat pinyinOutputFormat = new HanyuPinyinOutputFormat();
		pinyinOutputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		pinyinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		
		for(int i = 0;i < arr.length;i++) {
			if(arr[i] > 128) {
				try {
					String[] fullPinYin = PinyinHelper.toHanyuPinyinStringArray(arr[i],pinyinOutputFormat);
					// 获得首字母
					char temp = fullPinYin[0].charAt(0);
					builder.append(temp);
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					log.error(e.getMessage());
				}
			} else {
				builder.append(arr[i]);
			}
		}
		String firstSpell = builder.toString().replaceAll("\\W", "").trim();
		return firstSpell;
	}
}